package com.miao.im.biz;

import com.miao.im.common.Message;
import com.miao.im.common.annotation.MessageCommand;
import com.miao.im.common.enums.Command;
import com.miao.im.model.OfflineMsgRequestModel;
import com.miao.im.model.OfflineMsgResponseModel;
import com.miao.im.server.session.SessionContext;
import com.miao.im.server.session.SessionManager;
import com.miao.im.service.message.ChatMessage;
import com.miao.im.service.message.OfflineMessageManager;
import com.miao.im.support.handler.AbstractMessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
import reactor.util.context.ContextView;

import java.time.ZoneOffset;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/3/20 19:34
 * @Description:
 */
@Component
@MessageCommand(Command.OFFLINE_MSG_PULL)
@Slf4j
public class OfflineMsgPullRequestHandler extends AbstractMessageHandler<OfflineMsgRequestModel.OfflineMsgRequest> {
    @Autowired
    private OfflineMessageManager offlineMessageManager;


    @Override
    protected void doRead(OfflineMsgRequestModel.OfflineMsgRequest body, Message message) {

    }

    @Override
    protected Mono<Void> doDispatch(OfflineMsgRequestModel.OfflineMsgRequest body, Message message, SessionContext sessionContext) {
        log.info("收到离线消息拉取请求：{}-{}-{}", body.getLastTimestamp(), body.getPageSize(), body.getTargetType());
        return offlineMessageManager.getPersonalPage(Long.parseLong(sessionContext.getUserInfo().getUserId()),
                body.getTargetId(), body.getTargetType(),
                body.getLastTimestamp(), body.getPageSize())
                .doOnSuccess(chatMessages -> this.sendRespMsg(message, sessionContext, chatMessages))
                .then();

    }

    private void sendRespMsg(Message message, SessionContext sessionContext, List<ChatMessage> chatMessages) {
        List<OfflineMsgResponseModel.Content> collect = chatMessages.stream().map(msg -> {
            long sendTimestamp = msg.getSendTime().toInstant(ZoneOffset.of("+8")).toEpochMilli();
            return OfflineMsgResponseModel.Content.newBuilder()
                    .setFromUserId(msg.getFromUserId())
                    .setSequence(msg.getSequence())
                    .setTargetId(msg.getTargetId())
                    .setTargetType(msg.getTargetType())
                    .setMediaType(msg.getMediaType())
                    .setMessage(msg.getContent())
                    .setExpand(msg.getExpand())
                    .setSendTimestamp(sendTimestamp)
                    .build();
        }).collect(Collectors.toList());
        OfflineMsgResponseModel.OfflineMsgResponse msgResponse = OfflineMsgResponseModel.OfflineMsgResponse.newBuilder()
                .addAllMessages(collect)
                .build();
        Message response = Message.writeResponse(message.getVersion(), message.getSequence(), Command.OFFLINE_MSG_PULL.getCode(), msgResponse.toByteArray());
        SessionManager.send(sessionContext, response);
    }

}
